package com.sj.purchase.modules.cost.web.api;

import com.sj.purchase.modules.cost.domain.price.SkuAvgPriceId;
import com.sj.purchase.modules.cost.dto.SkuAvgPriceContainerDTO;
import com.sj.purchase.modules.cost.repository.order.SkuAvgPriceRepository;
import com.sj.purchase.common.Result;
import com.sj.purchase.modules.cost.domain.price.SkuAvgPrice;
import com.sj.purchase.modules.cost.dto.SkuAvgPriceDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.sj.purchase.common.ResultGenerator.ok;

/**
 * Created by yangrd on 2017/9/6
 **/
@RestController
@RequestMapping("/api/sku-avg")
public class SkuAvgPriceController {

    @Autowired
    private SkuAvgPriceRepository skuAvgPriceRepository;

    @PostMapping
    public Result<String> add(@RequestBody SkuAvgPriceContainerDTO skuAvgPriceContainerDTO) {
        Date createDate = skuAvgPriceContainerDTO.getCreateDate();
        List<SkuAvgPrice> skuAvgPriceList = skuAvgPriceContainerDTO.getList().stream().map(skuAvgPriceDTO -> this.conversion(skuAvgPriceDTO,createDate)).collect(Collectors.toList());
        skuAvgPriceRepository.save(skuAvgPriceList);
        return ok();
    }

    private SkuAvgPrice conversion(SkuAvgPriceDTO skuAvgPriceDTO, Date day) {
        SkuAvgPriceId skuAvgPriceId = new SkuAvgPriceId().setDay(day).setSkuNo(skuAvgPriceDTO.getCode());
        return new SkuAvgPrice().setId(skuAvgPriceId).setPrice(skuAvgPriceDTO.getCostPrice());
    }

}
